#!/usr/bin/env python
# -*- coding: utf-8 -*-

import feedparser
from sqlalchemy import *
import datetime

class AddFeedsFromFile(object):

    def __init__(self,sourceFile):
	##Connect to database
	self.db = create_engine('sqlite:///FAKE/helios.db')
	self.db.echo = False
	self.metadata = MetaData(self.db)
	#Map tables to objects
	self.sources = Table('sources', self.metadata, autoload=True)
	
	f = open(sourceFile) #use this to parse a feed

	for link in f:
	    result = self.db.execute(self.sources.select(self.sources.c.sourceURL == (link.replace('\n', ''))))
	    if result.fetchone() == None:
		print "Adding: " + link
		self.addFeed(link.replace('\n', ''), 'Unknown', 'Unknown')

    def addFeed(self, url, title, link):
	feed = feedparser.parse(url)
	    
	if feed.feed.has_key('title') == False:
	    feed.feed.title = title
	if feed.feed.has_key('link') == False:
	    feed.feed.link = link
	if feed.feed.has_key('description') == False:
	    feed.feed.description = ""
	if feed.feed.has_key('author') == False:
	    if feed.feed.has_key('publisher') == True:
		feed.feed.author = feed.feed.publisher
	    else:
		feed.feed.author = ""
	if feed.has_key('version') == False:
	    feed.version = ""

	i = self.sources.insert()
	i.execute(sourceURL=url, sourceTitle=feed.feed.title, sourceOwner=feed.feed.author, sourceLink=feed.feed.link, sourceDescription=feed.feed.description, sourceSpecification=feed.version, sourceUpdateInterval=300, sourceLastChecked=datetime.datetime(1970,1,1,0,0,0), sourceEtag="", sourceLastModified=datetime.datetime(1970,1,1,0,0,0), sourceUsability=0, sourceFavourite=0)